// @fm:on
/**
 * @ ver.Core : v1.1.3 bate
 * @ author   : Jason.C
 * @ email    : czymuzi@163.com, chenzy@evmtv.com
 * @ update   : 2013/10/21 02:00
 *                          01. 优化上下文形参传入格式 . 可直接传入 "#ID"
 *                          02. 重写选择器, 添加关系语法支持 . ** “>”、“ ”、“,” 以及 它们的混合用法 ( 越复杂的规则效率上越差 )
 *                          03. 优化 trim 函数的左右裁剪的功能 .
 *                          04. 修改 html, append、prepend、after、before 写入的 HMTL 中带有 script 时没有执行脚本的问题
 *                          05. 添加 getElementsByClassName 的支持
 *                          06. 去除存在问题的 getAllDate 函数 ( 暂时没有找到替代的方法 )
 *                          07. 为 ajax 添加 get、post 简易使用方法
 *                          08. 修改 class 操作几处实现错误问题
 *                          09. 修改几处 BUG
 *                          10. 添加 $ 命名空间的判断
 *                          11. 添加几个小方法
 *                          12. 添加 $().load() 方法
 * 
 *  @@ 新的版本依旧还没有添加动画的支持, 以及 find 的支持, 暂时没有找到比较好的解决方法!
 *  @@ 各个厂家的机顶盒浏览器的兼容性还需要进一步测试!
 **/

( function ( window, undefined ) {
Number.prototype.fixLen = String.prototype.fixLen = function ( _str )
{
    var _this = this.toString( );
    var _iLen = _str.toString( ).length | 0;
    _this = "" + _str + _this;
    var iLength = _this.length;
    _this = _this.substr( iLength - _iLen );
    return _this;
};
String.prototype.trim = function ( P )
{
    var _this = this.toString( );
    return _this.replace( (P == "left") ? /^(\s|\u00A0)+/ : ( ( P == "right" ) ? /(\s|\u00A0)+$/ : /^(\s|\u00A0)+|(\s|\u00A0)+$/g ), "" );
};

Date.prototype.printf = function ( string ) {
    var _T = this;
    var weekStr_CN = [ "日", '一', '二', '三', '四', '五', '六' ];
    
    function trim ( S, L, T ) {
        var
            S = S.toString(),
            S = S.length < L ? ( Math.pow( 10, ( L-S.length ) )+""+ S).substr(1) : S,
            L = T.indexOf("Y") == -1 ? (S.length >= L ? S.length : L) : L ;
        return S.substr( S.length - L );
    }
    function replace ( R, D ) {
        var R = string.match( R );
        return R ? string.replace( R.toString(), trim( D, R.toString().length, R.toString() ) ) : string;
    }
    if ( string ) {
        string = string.replace ( /W/, weekStr_CN[_T.getDay()] );
        string = replace( /Y+/, _T.getFullYear() );
        string = replace( /M+/, _T.getMonth() + 1 );
        string = replace( /D+/, _T.getDate() );
        string = replace( /h+/, _T.getHours() );
        string = replace( /m+/, _T.getMinutes() );
        string = replace( /s+/, _T.getSeconds() );
        _T = string;
    }
    return _T;
}

var
    version     = '1.1.3 bate',
    _$          = window.$,
    undefined   = undefined,
    noop        = new Function (),
    _readyLoader_ = [],
    userAgent   = navigator.userAgent,

    slice       = Array.prototype.slice,
    toString    = Object.prototype.toString,
    indexOf     = Array.prototype.indexOf,
    
    Expr = {
        isSimple: /^.[^:#\[\.,\s>]*$/,
        isId    : /#((?:[\w\u00c0-\uFFFF-]|\\.)+)/,
        isClass : /\.((?:[\w\u00c0-\uFFFF-]|\\.)+)/,
        isTag   : /^((?:[\w\u00c0-\uFFFF\*-]|\\.)+)/
    },
    
    typeOf = function ( _O, _P ) {
        var RET = toString.call( _O ).slice( 8, -1 ).toLowerCase();
        return typeof _P === "string" ? ( new RegExp ( RET + '[^A-Za-z]|'+ RET +'$', 'gi' ).test( _P ) ) : RET;
    },
    
    $ = jPure = function ( _selector, _context )
    {
        return new jPure.plu.selector ( _selector, _context );
    };

jPure.plu =
{
    jPure: version,
    constructor : jPure,
    selector : function ( _selector, _context )
    {
        if ( !_selector ) return this;
        if ( typeOf( _selector, 'function' ) ) return this.ready( _selector );
        var _context = ( !_context || !(typeof _context == "string") ? document : ( _context.nodeType ? _context : document.getElementById(_context.substring(1) ) ) ) || document;
        if ( _selector.nodeType )
        {
            this.context = this[ 0 ] = _selector;
            this.length = 1;
            return this;
        }
        if ( typeof _selector === "string" )
        {
            var HTMLElement = [];
            if ( document.querySelectorAll ){
                HTMLElement = slice.call( document.querySelectorAll( _selector ) );
            }
            else
            {
                var sRules = _selector = _selector.trim().replace(/\s+(,|>|\+)\s*|\s+/g, "$1 ");
                HTMLElement = HandleRule( sRules.replace(/>\s/g, ">"), _context );
            }
            
            this.extend( HTMLElement );
            this.context = _context;
            this.selector = _selector;
            this.length = HTMLElement.length;
            return this;
        }
    },
    ready : function ( _Function ) {
        var $this = this;
        typeof _Function == "function" && _readyLoader_.push( _Function );
        1 == _readyLoader_.length && addListener.call( document, "readystatechange", function ( ) {
            if ( document.readyState == "complete" )
                for ( var i = 0, iMax = _readyLoader_.length; i < iMax; i++ )
                    _readyLoader_[ i ].apply( $this );
        } );
            return this;
    },
    
    each : function ( _callback, args )
    {
        return jPure.each( this, _callback, args );
    },
    
    length : 0,
    push : [].push,
    sort : [].sort,
    splice : [].splice,
    index : function ( _ser )
    {
        var ret = null, self = this;
        if ( self.nodeType == 1 )
        {
            self.each( function ( index )
            {
                if ( self[ index ] == _ser ) ret = index;
            } );
            return parseInt( ret );
        }
        if ( _ser != undefined && ( 0 <= _ser && _ser < self.length ) ) return jPure( self[ _ser ] );
        return self;
    }
};

jPure.plu.selector.prototype = jPure.plu;
jPure.extend = jPure.plu.extend = function ( _Object, _Target )
{
    var _Target = _Target || this;
    if ( !_Object ) return false;
    for ( var name in _Object ) _Target[ name ] = _Object[ name ];
    return _Target;
};

jPure.each = function ( _object, _callback, _args )
{
    var _args = _args || [ ], _object = _object || this, _callback = _callback || noop;
    var idx = 0, length = _object.length, argLen = _args.length;
    
    if ( length > 0 )
    {
        for ( ; idx < length; idx++ )
        {
            _args[ argLen ] = idx;
            _callback.apply( _object[ idx ], _args );
        }
    }
    return _object;
}

jPure.extend({
    isArray : function ( _obj )
    {
        return toString.call( _obj ) === "[object Array]";
    },
    isFunction: function( obj )
    {
        return toString.call( obj ) === "[object Function]";
    },
    isNullObject : function ( _obj )
    {
        for ( var m in _obj ) return !1;
        return !0;
    },
    inArray: function ( _E, _A )
    {
        if ( _A.indexOf ) return _A.indexOf( _E );
        for ( var i = 0, length = _A.length; i < length; i++ ) if ( _A[ i ] === _E ) return i;
        return -1;
    },
    toArray : function( _obj )
    {
        return slice.call( _obj, 0 );
    },
    
    mergeArray : function ( _A, _T )
    {
        var self = this, _T = _T || [];
        if ( self.isArray( _A ) ) for ( var i in _A ) if ( self.inArray(_A[i], _T ) == -1 ) _T.push( _A[i] );
        return _T;
    },
    get : function ( _url, _callback, _type )
    {
        return jPure.ajax({ type: "GET", url: _url, success: _callback, dataType: _type || "text" });
    },
    post : function ( _url, _callback, _data, _type )
    {
        return jPure.ajax({ type: "POST", url: _url, success: _callback, data: _data || null, dataType: _type || "text" });
    },
    ajax : function ( _config )
    {
        var _default = jPure.extend(
                    _config || {},
                    { "async" : true, "cache" : false, "data" : null, "type" : "GET", "url" : null, "dataType" : 'text', "complete" : noop, "success" : noop, "error" : noop}
            );
        
        _default.dataType = _default.dataType.toLowerCase();
        _default.type = _default.type.toUpperCase();
        if ( _default.dataType == 'jsonp' ) return this.getJSONP( _default.url, _default.complete, 'utf-8' );
        var xmlHttpRequest;
        try {
            xmlHttpRequest = new XMLHttpRequest ();
        } catch( a ) {
            try {
                xmlHttpRequest = new ActiveXObject ( "Msxml2.XMLHTTP" );
            } catch( b ) {
                try {
                    xmlHttpRequest = new ActiveXObject ( "Microsoft.XMLHTTP" );
                } catch( c ) {
                    console.error( "XMLHttpRequest 对象创建失败, 您的浏览器似乎不支持异步获取数据!");
                    return; 
                }
            }
        }
        if ( !xmlHttpRequest || !_default.url ) return;
        if ( !_default.cache ) _default.url += ( ( _default.url.indexOf("?") == -1 ) ? "?" : "&" ) + ( "jPure_" + new Date().getTime() + jPure.random(1000, 9999) );
        xmlHttpRequest.open( _default.type, _default.url, _default.async );
        if ( _default.type == "POST")
        {
            xmlHttpRequest.setRequestHeader( "If-Modified-Since", "0" );
            xmlHttpRequest.setRequestHeader( "Cache-Control", "no-cache" );
            xmlHttpRequest.setRequestHeader( "Content-Type", "application/x-www-form-urlencoded" );
        }
        xmlHttpRequest.onreadystatechange = function ( )
        {
            if ( xmlHttpRequest.readyState == 4 )
            {
                _default.complete.call( this, xmlHttpRequest );
                if ( xmlHttpRequest.status == 200 )
                {
                    _default.success.call( this, jPure.parseJSON( xmlHttpRequest.responseText ) );
                }
                else if ( xmlHttpRequest.status >= 400 )
                {
                    _default.error.call( this, { "errCode": xmlHttpRequest.status, "errInfo" : xmlHttpRequest.statusText } );
                }
            }
        };
        xmlHttpRequest.send( _default.data );
    },

    getJSONP : function ( _url, _callback, _charset )
    {
        if ( !_url ) return;
        var caller = "callback";
        var iStart = _url.indexOf( "caller=" );
        if ( iStart > -1 )
        {
            var callerName = _url.substring(iStart).split("=")[ 1 ];
            caller = ( callerName || callerName != "?" ) ? callerName : "callback";
        }
        var box = document.getElementsByTagName("head")[ 0 ];
        var jsonScripBox = document.createElement( "script" );
        with ( jsonScripBox )
        {
            type = "text/javascript";
            charset = _charset || "utf-8";
            src = _url;
            onload = function ( )
            {
                box.removeChild( jsonScripBox );
            };
        }
        window[ caller ] = jPure.isFunction( _callback ) ? _callback : noop;
        box.appendChild( jsonScripBox );
    },
    random : function ( a, b )
    {
        var a = a | 0, b = b | 10;
        return ( a + Math.round( Math.random( ) * Math.abs( b - a ) ) );
    },
    parseJSON : function ( D )
    {
        var R;
        try {
            R = (new Function("return " + D) )();
        } catch(E) {
            try{
                R = eval( "("+ D +")" );
            } catch ( e ) {
                R = D;
            }
        }
        return R;
    },
    getElementsByClassName: function ( _classNames, _parentElement )
    {
        var item = ( _parentElement || document.body ).getElementsByTagName("*"), ret=[];
        try {
            var _classItem = _classNames.trim().replace(/\s+/g, " ").replace(/\./, "").split(" ");
        } catch ( e ) {
            // console.error( "传入参数解析错误，可能是由于格式不正确引起的。请传入由一个或多个 'className' 组成的字符串.\n出错信息: [ " + e.message + " ]");
            return [];
        }
        for ( var x = 0; name = _classItem[x]; x++ )
        {
            if ( ret.length > 0 ) item = ret, ret=[];
            for (var i = 0; e = item[i]; i++) if ( (' ' + ( e.className.trim().replace(/\s+/, ' ') ) + ' ').indexOf( (' ' + name + ' ') ) != -1 ) ret.push( e );
        }
        return ret; 
    },
});

var
    _isSimple = function ( _tRule, _context )
    {
        var Or = Expr.isId.test( _tRule ) ? 1 : Expr.isTag.test( _tRule ) ? 2 : Expr.isClass.test( _tRule ) ? 3 : 0 ;
        return Or==1 ? [ _context.getElementById( _tRule.substring(1) ) ]:
               Or==2 ? jPure.toArray( _context.getElementsByTagName( _tRule ) ):
               Or==3 ? slice.call( jPure.getElementsByClassName( _tRule.substring(1), _context ) ) : [];
    },
    HandleRule = function( _rule, _context )
    {
        var gRules = _rule.split(', '), result = [];
        for ( var i = 0; i < gRules.length; i++ )
        {
            var CR = gRules[ i ];
            if ( CR.indexOf( ' ' )  == -1 && CR.indexOf( '>' )  == -1 )
            {
                var newSimple = _isSimple( CR, _context );
                if ( !result.length )
                    result = newSimple;
                else
                    for ( var n=0; n < newSimple.length; n++ )
                        if ( jPure.inArray( newSimple[ n ] , result ) == -1 ) result.push( newSimple[ n ] );
            }
            else
            {
                if ( gRules[ i ].indexOf( ' ' ) > -1  )
                {
                    var nParent = [ _context ];
                    for ( var i=0, gRulesChilds = CR.split(" "), iLen = gRulesChilds.length; i < iLen; i++ )
                    {
                        var curRuld = gRulesChilds[i], rParents = [];
                        for (var p in nParent)
                        {
                            var tmpRuleResult = arguments.callee( curRuld, nParent[p] );
                            if ( tmpRuleResult[0] ) for ( var x in tmpRuleResult ) if ( jPure.inArray( tmpRuleResult[x], rParents ) == -1 ) rParents.push( tmpRuleResult[x] );
                        }
                        nParent = rParents;
                    }
                    result = nParent;
                }
                else if ( gRules[ i ].indexOf( '>' ) > -1  )
                {
                    var gRuleNode = gRules[ i ].split('>').reverse();
                    var target = arguments.callee( gRuleNode.shift().toString(), _context);
                    for ( var t in target )
                    {
                        var tParent = target[ t ].parentElement, isResult = 0;
                        for ( var r in gRuleNode )
                        {
                            var nParents = arguments.callee( gRuleNode[r], _context );
                            var inArrayIndex = jPure.inArray( tParent, nParents );
                            if ( inArrayIndex != -1 )
                            {
                                tParent = nParents[ inArrayIndex ].parentElement;
                                isResult = 1;
                            }
                            else
                            {
                                isResult = 0;
                                break;
                            }
                        }
                        if ( isResult ) result.push( target[ t ] );
                    }
                }
            }
        }
        return result.length == 0 ? [null] : result ;
    },
    
    _runJS = function ( _E )
    {
        var
           C = document.createElement('div'),
           S = C.getElementsByTagName('script');

        C.innerHTML = _E;
        var box = document.getElementsByTagName("head")[0];
        for (var i=0, iLen = S.length; i< iLen; i++)
        {
            var J = document.createElement('script');
            J.type = "text/javascript";
            if ( S[i].src )
                S[i].src = J.src;
            else
                J.text = S[i].text;
            box.removeChild( box.appendChild( J ) );
        }
        return _E;
    }
if ( !document.getElementsByClassName ) document.getElementsByClassName = jPure.getElementsByClassName;
window[ ( _$ != undefined ? "jP" : "$" ) ] = jPure;
jPure.plu.extend( {
    css : function ( _key, _value )
    {
        var _key = _key, _value = _value, self = this;
        if ( !self[0] ) return self;
        if ( typeof _value == "string" )
        {
            self.each( function ( _key, _value )
            {
                this.style[ _key ] = _value;
            }, [ _key, _value ] );
            return self;
        }
        if ( typeof _key == "string" ) return window.getComputedStyle(self[0], null)[ _key ];
        if ( typeof _key == "object" )
        {
            return self.each( function ( _obj )
            {
                var styleCss = "";
                for ( var k in _obj ) styleCss += ( k + ': ' + _obj[ k ] + '; ' );
                this.style.cssText = styleCss;
            }, [ _key ] );
        }
    },
    width: function ( _v )
    {
        return this.css( "width", _v != undefined ? _v : undefined );
    },
    height : function ( _v )
    {
        return this.css( "height", _v != undefined ? _v : undefined );
    },
    top : function ( _v )
    {
        return this.css( "top", _v != undefined ? _v : undefined );
    },

    left : function ( _v )
    {
        return this.css( "left", _v != undefined ? _v : undefined );
    },
    hide : function ( _S, _C )
    {
        return this.css( "display", "none" );
    },
    show : function (  _S, _C )
    {
        return this.css( "display", "" );
    }
} );

jPure.plu.extend({ animate: function ( _params, _speed, _callback ) {} });
jPure.plu.extend( {
    addClass: function ( _N )
    {
        var _N = _N.trim().replace( /\s+/g, " " );
        if ( _N )
        {
            _N = _N.split(" ");
            for ( var i in _N )
                this.each( function ( _N )
                {
                    var CN = this.className;
                    if ( !CN ) this.className = _N;
                    else if ( jPure.inArray( _N, slice.call( CN )) == -1 ) this.className += (" " + _N);
                    
                }, [ _N[i] ] );
        }
        return this;
    },
    className : function ( _N )
    {
        if ( !_N ) return this[ 0 ].className;
        return this.each( function ( _N )
        {
            this.className = _N;
        }, [ _N ] );
    },
    hasClass : function ( C )
    {
        if ( C ) for ( var i =0, len=this.length; i<len; i++ ) if ( jPure.inArray( C.replace(/\s+/g, ""), slice.call( this[i].classList ) ) != -1 ) return true;
        return false;
    },
    removeClass : function ( _N )
    {
        var _N = _N.trim( ).replace( /\s+/g, " " );
        if ( _N )
        {
            _N = _N.split( ' ' );
            this.each( function ( _N )
            {
                var cEle = this;
                for ( var n in _N )
                {
                    if ( !cEle.className ) break;
                    var target = " " + slice.call( cEle.classList ).join(" ") + " ";
                    for ( var i in _N ) if ( target.indexOf( (" " + _N[ i ] + " ") ) > -1 ) target = target.replace( _N[ i ], "" );
                    cEle.className = target.trim();
                }
            }, [ _N ] );
        }
        return this;
    }
} );
jPure.plu.extend({
    src : function ( _S )
    {
        if ( _S != undefined )
        {
            return this.each( function ( _S )
            {
                if ( _S != this.src ) this.src = _S;
            }, [ _S ] );
        }
        return this[ 0 ].src;
    },
    html : function ( E )
    {
        if ( E != undefined )
        {
            this.each( function ( E )
            {
                if ( E != this.innerHTML ) this.innerHTML = E;
            }, [ E ] );
            _runJS( E );
            return this;
        }
        return this[ 0 ].innerHTML;
    },
    text : function ( t )
    {
        if ( t != undefined )
        {
            this.each( function ( t )
            {
                if ( t != this.innerText ) this.innerText = t;
            }, [ t ] );
            return this;
        }
        return this[ 0 ].innerText;
    },
    append : function ( E )
    {
        if ( E != undefined )
        {
            this.each( function ( E )
            {
                this.innerHTML += E;
            }, [ E ] );
            _runJS( E );
        }
        return this;
    },
    prepend : function ( E )
    {
        if ( E != undefined )
        {
            this.each( function ( E )
            {
                this.innerHTML = E + this.innerHTML;
            }, [ E ] );
            _runJS( E );
        }
        return this;
    },
    after : function ( E )
    {
        if ( E != undefined )
        {
            this.each( function ( E )
            {
                this.outerHTML = this.outerHTML + E;
            }, [ E ] );
            _runJS( E );
        }
        return this;
    },
    before : function ( E )
    {
        if ( E != undefined )
        {
            this.each( function ( E )
            {
                this.outerHTML = E + this.outerHTML;
            }, [ E ] );
            _runJS( E );
        }
        return this;
    },
    load: function ( _URL )
    {
        var self = this;
        jPure.ajax({ async: false, cache: true, url: _URL, success: function ( R ) {
            self.html( R );
        } });
        return this;
    }
});
jPure.extend(
{
    preloadImage : function ( _imageURL, imgElement )
    {
        var imgObject;
        if ( typeof ( _imageURL ) == "string" )
        {
            imgObject = new Image ( );
            imgObject.src = _imageURL;
        }
        else
        {
            for ( var i = 0; i < _imageURL.length; i++ )
            {
                imgObject = imgElement ? imgElement[ i ] : new Image ( );
                imgObject.src = _imageURL[ i ];
            }
        }
    },
    getRequest : function ( S, K )
    {
        if ( !S ) return {};
        var S = S.substring(1).split("&"), ret = {};
        for (var i in S)
        {
            var retChild = S[i].split("=");
            ret[retChild[0]] = retChild[1] === undefined ? null : retChild[1] ;
        }
        if ( K === undefined ) return ret;
        return ret[K];
    },
    typeOf : typeOf,
    escapeParam : function ( _href )
    {
        var filePath = _href.match( /http\:\/\/[\w\-_]+(\.[\w\-_]+)+[^#\?]*/g ).toString();
        _h = _href.replace( filePath, '' ).replace( /#.*$/, '' );
        _h = _h.match( /[^\?\&\#]+=[^\&]*/g );
        var ret = '';
        for ( var i = 0; i < _h.length; i++ ) {
            ret += _h[i].split("=")[ 0 ] + "=" + escape( _h[i].split("=")[ 1 ] ) + "&";
        }
        return filePath + ret.replace( /&$/g, '' );
    }
} );

//----------------------
//_ Good lucky 
})( window );